<?php
// +----------------------------------------------------------------------
// | Variable 自定义服务
// +----------------------------------------------------------------------
// | 主要服务于Variable数据处理
// +----------------------------------------------------------------------
// | 错误编码头 230xxx
// +----------------------------------------------------------------------

namespace common\service;

use common\model\FieldModel;
use common\model\ModuleModel;
use Exception;
use support\bootstrap\Redis;
use support\SingletonTrait;

class FieldService
{

    // 上一次刷新字段时间
    const MODULE_CONFIG_REFRESH_KEY = 'module_config_fresh_time_key';
    // 上一次生成内存字段缓存时间
    private static int $moduleFieldMakeTime = 0;

    /**
     * @var FieldModel
     */
    protected $fieldModel;

    // 单例工具
    use SingletonTrait;

    public function __construct()
    {
        $this->fieldModel = model(FieldModel::class);
    }

    /**
     * 获取单张表配置
     * @param string $tableName
     * @return array
     */
    public function getFieldConfig(string $tableName = '')
    {
        if (!empty($tableName)) {
            // 判断是否传入表名称
            $resData = $this->fieldModel->getTableFields($tableName);
        } else {
            $resData = ["total" => 0, "rows" => []];
        }
        return $resData;
    }

    /**
     * 修改
     * @param string $tableName
     * @param array $config
     * @return array
     * @throws Exception
     */
    public function modifyFieldConfig(string $tableName = '', array $config = [])
    {
        return $this->fieldModel->modifyFieldConfig($tableName, $config);
    }

    /**
     * 自动刷新字典配置和缓存
     */
    public function autoFixFieldConfigAndCache()
    {
        $moduleModel = model(ModuleModel::class);
        $moduleList = $moduleModel->field('code')->select();

        // 获取最新字段配置然后写回去
        foreach ($moduleList as $item) {
            $newFields = $this->getFieldConfig($item['code']);

            // 分开固定字段和自定义字段
            $saveFields = [
                'custom' => [],
                'fixed' => []
            ];
            foreach ($newFields as $field) {
                if ($field['field_type'] === 'built_in') {
                    $saveFields['fixed'][] = $field;
                } else {
                    $saveFields['custom'][] = $field;
                }
            }

            // 更新字段配置
            $this->modifyFieldConfig($item['code'], $saveFields);
        }

        // 更新模块字段缓存
        Redis::set(self::MODULE_CONFIG_REFRESH_KEY, time());
//        $this->generateModuleFieldCache();
    }

}
